package 剑指offer_leetcode;

import java.util.PriorityQueue;

/**
 * JZ40最小的K个数
 */
public class 剑指Offer40_最小的k个数 {
    public int[] getLeastNumbers(int[] arr, int k) {
        if(arr.length==0 || k<=0 || k>arr.length)
            return new int[0];
        PriorityQueue<Integer> q = new PriorityQueue<>((o1, o2)->o2.compareTo(o1));
        for(int i=0;i<k;i++)
            q.offer(arr[i]);
        for(int i=k;i<arr.length;i++){
            if(q.peek()>arr[i]){
                q.poll();
                q.offer(arr[i]);
            }
        }
        int[] res = new int[q.size()];
        int i=0;
        while(!q.isEmpty())
            res[i++] = q.poll();
        return res;
    }
}
